package com.controller;

import com.bean.Msg;
import com.bean.User;
import com.bean.UserType;
import com.bean.UserType;

import com.service.IUserService;
import com.shiro.token.CustomLoginToken;
import com.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * 后台登录controller
 * @author WxrStart
 * @create 2022-05-22 21:53
 */
@Controller
@Slf4j
@RequestMapping("/admin")
public class AdminController {

@Autowired
private IUserService iUserService;
    /**
     * 后台管理页面（必须要是admin用户）
     * @return
     */
    @GetMapping("/index")
    @ResponseBody
    public Msg gotoBGindex(){
        log.info("进入到了后台管理页面主页");
        Subject subject = SecurityUtils.getSubject();
        if(subject.hasRole("admin")) {
            return Msg.success().add("result","登陆成功");
        } else {
            //无权限
            Msg fail = Msg.fail();
            fail.setCode(401);
            fail.add("result","登录失败，该用户没有权限");
            return fail;
        }
    }


    /**
     * 后台登录页面提交
     * @param loginuser
     * @param response
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public Msg adminLogin(@RequestBody User loginuser,HttpServletResponse response) {
        log.info("提交数据到了后台管理页面登录页");
        String email = loginuser.getEmail();
        String password = loginuser.getPassword();
        User user =iUserService.findByEmail(email);
        if (user == null) {
            throw new UnknownAccountException();
        }
        //判断用户是否被冻结
        if (user.getStatus()!=1) {
            throw new LockedAccountException("该用户已被冻结,暂时无法登录！");
        }
        // 将用户名和密码封装成 UsernamePasswordToken 对象
        CustomLoginToken token = new CustomLoginToken(email,password,user.getUserRole());
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
        if(!user.getUserRole().equals(UserType.ADMIN.toString())){
            throw new AuthenticationException("该用户没有权限访问后台");
        }
        // 若登录成功，签发 JWT token
        String jwtToken = JWTUtils.sign(email,user.getUserRole(),JWTUtils.SECRET);
        // 将签发的 JWT token 设置到 HttpServletResponse 的 Header 中
         response.setHeader(JWTUtils.AUTH_HEADER, jwtToken);
        return Msg.success().add("result","登陆成功").add("jwt",jwtToken);
    }




}
